<template>
  <div class="search-page">
    <!-- 导航栏 -->
    <NavBar title="搜索" />
    
    <!-- 搜索栏 -->
    <div class="search-header">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索内容..."
        @search="handleSearch"
        @clear="handleClear"
        show-action
        autofocus
      >
        <template #action>
          <div @click="handleSearch" class="search-action">搜索</div>
        </template>
      </van-search>
    </div>
    
    <!-- 搜索结果 -->
    <div class="search-content" v-if="hasSearched">
      <!-- 分类筛选 -->
      <div class="filter-tabs">
        <van-tabs v-model:active="activeType" @change="handleTypeChange">
          <van-tab title="全部" name="all" />
          <van-tab title="表白墙" name="board" />
          <van-tab title="兼职" name="job" />
          <van-tab title="失物" name="lost" />
          <van-tab title="闲置" name="leave" />
          <van-tab title="新闻" name="news" />
        </van-tabs>
      </div>
      
      <!-- 搜索结果列表 -->
      <div class="result-list">
        <div 
          v-for="item in resultList" 
          :key="item.id"
          class="result-item card"
          @click="goToDetail(item)"
        >
          <!-- 类型标签 -->
          <div class="item-header">
            <van-tag :type="getTagType(item.type)" size="mini">
              {{ getTypeName(item.type) }}
            </van-tag>
            <span class="time">{{ formatTime(item.createTime) }}</span>
          </div>
          
          <!-- 内容 -->
          <div class="item-content">
            <div class="title">{{ item.title }}</div>
            <div class="content">{{ item.content }}</div>
            
            <!-- 图片 -->
            <div class="images" v-if="item.images && item.images.length">
              <img 
                v-for="(img, index) in item.images.slice(0, 3)" 
                :key="index"
                :src="img" 
                alt="图片"
                class="content-image"
              />
            </div>
          </div>
          
          <!-- 底部信息 -->
          <div class="item-footer">
            <div class="user-info">
              <img :src="item.userAvatar || '/images/default-avatar.png'" alt="头像" class="avatar" />
              <span class="nickname">{{ item.userNickname }}</span>
            </div>
            <div class="stats">
              <span class="stat-item">
                <van-icon name="eye-o" size="12" />
                {{ item.viewCount }}
              </span>
              <span class="stat-item">
                <van-icon name="chat-o" size="12" />
                {{ item.commentCount }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore">
        <van-button 
          :loading="loading" 
          @click="loadMore"
          type="default"
          size="small"
        >
          {{ loading ? '加载中...' : '加载更多' }}
        </van-button>
      </div>
      
      <!-- 空状态 -->
      <van-empty 
        v-if="!loading && resultList.length === 0"
        description="没有找到相关内容"
        image="search"
      />
    </div>
    
    <!-- 搜索建议 -->
    <div class="search-suggestions" v-else>
      <div class="suggestions-section">
        <h3 class="section-title">热门搜索</h3>
        <div class="suggestion-tags">
          <van-tag 
            v-for="tag in hotTags" 
            :key="tag"
            @click="searchTag(tag)"
            class="suggestion-tag"
          >
            {{ tag }}
          </van-tag>
        </div>
      </div>
      
      <div class="suggestions-section">
        <h3 class="section-title">搜索历史</h3>
        <div class="history-list">
          <div 
            v-for="(history, index) in searchHistory" 
            :key="index"
            class="history-item"
            @click="searchTag(history)"
          >
            <van-icon name="clock-o" size="16" color="#999" />
            <span class="history-text">{{ history }}</span>
            <van-icon 
              name="cross" 
              size="14" 
              color="#999" 
              @click.stop="removeHistory(index)"
            />
          </div>
        </div>
        
        <div class="clear-history" v-if="searchHistory.length > 0">
          <van-button 
            type="default" 
            size="small" 
            @click="clearHistory"
          >
            清空历史
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavBar from '@/components/Common/NavBar.vue'
import { searchApi } from '@/api'
import { formatTime } from '@/utils/time'
import { useAppStore } from '@/stores/app'

const router = useRouter()
const appStore = useAppStore()

// 设置页面标题
appStore.setTitle('搜索')

// 响应式数据
const searchKeyword = ref('')
const activeType = ref('all')
const resultList = ref<any[]>([])
const loading = ref(false)
const hasMore = ref(true)
const hasSearched = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 搜索历史
const searchHistory = ref<string[]>([])
const hotTags = ref(['表白', '兼职', '失物', '二手', '招聘', '校园'])

// 类型映射
const typeNames = {
  board: '表白墙',
  job: '兼职招聘',
  lost: '失物招领',
  leave: '闲置买卖',
  news: '新闻公告'
}

const tagTypes = {
  board: 'primary',
  job: 'success',
  lost: 'warning',
  leave: 'danger',
  news: 'default'
}

// 搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    showToast('请输入搜索关键词')
    return
  }
  
  // 添加到搜索历史
  addToHistory(searchKeyword.value)
  
  hasSearched.value = true
  currentPage.value = 1
  await loadResults(true)
}

// 清除搜索
const handleClear = () => {
  searchKeyword.value = ''
  hasSearched.value = false
  resultList.value = []
}

// 类型切换
const handleTypeChange = () => {
  currentPage.value = 1
  loadResults(true)
}

// 加载搜索结果
const loadResults = async (isRefresh = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const params = {
      keyword: searchKeyword.value,
      type: activeType.value === 'all' ? '' : activeType.value,
      page: isRefresh ? 1 : currentPage.value,
      size: pageSize
    }
    
    const response = await searchApi.search(params)
    const { list, total } = response.data
    
    if (isRefresh) {
      resultList.value = list
      currentPage.value = 1
    } else {
      resultList.value.push(...list)
    }
    
    hasMore.value = resultList.value.length < total
    currentPage.value++
  } catch (error) {
    showToast('搜索失败')
    console.error('搜索失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  loadResults()
}

// 搜索标签
const searchTag = (tag: string) => {
  searchKeyword.value = tag
  handleSearch()
}

// 跳转到详情
const goToDetail = (item: any) => {
  const routes = {
    board: `/board/${item.id}`,
    job: `/job/${item.id}`,
    lost: `/lost/${item.id}`,
    leave: `/leave/${item.id}`,
    news: `/news/${item.id}`
  }
  
  const route = routes[item.type as keyof typeof routes]
  if (route) {
    router.push(route)
  }
}

// 获取类型名称
const getTypeName = (type: string) => {
  return typeNames[type as keyof typeof typeNames] || type
}

// 获取标签类型
const getTagType = (type: string) => {
  return tagTypes[type as keyof typeof tagTypes] || 'default'
}

// 添加到搜索历史
const addToHistory = (keyword: string) => {
  const history = searchHistory.value.filter(item => item !== keyword)
  history.unshift(keyword)
  searchHistory.value = history.slice(0, 10) // 最多保存10条
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 删除搜索历史
const removeHistory = (index: number) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 初始化搜索历史
const initHistory = () => {
  const saved = localStorage.getItem('searchHistory')
  if (saved) {
    try {
      searchHistory.value = JSON.parse(saved)
    } catch (error) {
      console.error('解析搜索历史失败:', error)
    }
  }
}

// 页面加载时初始化
onMounted(() => {
  initHistory()
})
</script>

<style scoped>
.search-page {
  min-height: 100vh;
  background-color: #f1f1f1;
}

.search-header {
  background: white;
  padding: 8px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.search-action {
  color: #636DEA;
  font-size: 16px;
  cursor: pointer;
}

.search-content {
  padding: 0 16px 16px;
}

.filter-tabs {
  background: white;
  border-radius: 8px;
  margin: 16px 0;
  overflow: hidden;
}

.result-list {
  margin-bottom: 16px;
}

.result-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.time {
  font-size: 12px;
  color: #999;
}

.item-content {
  margin-bottom: 12px;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 6px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.images {
  display: flex;
  gap: 6px;
}

.content-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.item-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 12px;
  color: #333;
}

.stats {
  display: flex;
  gap: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 16px 0;
}

.search-suggestions {
  padding: 16px;
}

.suggestions-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-tag {
  cursor: pointer;
}

.history-list {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.history-item:last-child {
  border-bottom: none;
}

.history-item:hover {
  background-color: #f8f9fa;
}

.history-text {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.clear-history {
  text-align: center;
  margin-top: 16px;
}
</style>